package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.common.converter;

import com.fasterxml.jackson.databind.JsonNode;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.StringUtils;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.ScriptTask;
import org.flowable.bpmn.model.UserTask;
import org.flowable.editor.language.json.converter.BaseBpmnJsonConverter;
import org.flowable.editor.language.json.converter.BpmnJsonConverterUtil;
import org.flowable.editor.language.json.converter.ScriptTaskJsonConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author: niechanggang
 * @date:2021/8/6 8:58
 * @description:
 */
public class CustomScriptTaskJsonConverter  extends ScriptTaskJsonConverter {

    private  static Logger  logger = LoggerFactory.getLogger(CustomScriptTaskJsonConverter.class);

    public static void fillTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap, Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap) {

        fillJsonTypes(convertersToBpmnMap);
        fillBpmnTypes(convertersToJsonMap);
    }

    public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
        convertersToBpmnMap.put(STENCIL_TASK_SCRIPT, CustomScriptTaskJsonConverter.class);
    }

    public static void fillBpmnTypes(Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap) {
        convertersToJsonMap.put(ScriptTask.class, CustomScriptTaskJsonConverter.class);
    }

    @Override
    protected FlowElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap) {
        ScriptTask task = new ScriptTask();
        //JsonNode baseInfo =  elementNode.get("baseInfo");
        JsonNode  propsNode = elementNode.get("properties");
        //JsonNode baseInfo =  propsNode.get("baseInfo");
        JsonNode scriptConf =  propsNode.get("scriptConf");
        //String code = BpmnJsonConverterUtil.getValueAsString("code", baseInfo);
        //String name = BpmnJsonConverterUtil.getValueAsString("name", baseInfo);
        String scriptText = BpmnJsonConverterUtil.getValueAsString("scriptText", scriptConf);
        String resultVariable = BpmnJsonConverterUtil.getValueAsString("resultVariable", scriptConf);
        String scriptFormat = BpmnJsonConverterUtil.getValueAsString("scriptFormat", scriptConf);
        String autoStoreVariables = BpmnJsonConverterUtil.getValueAsString("autoStoreVariables", scriptConf);
        task.setScriptFormat(scriptFormat.toLowerCase());
        task.setScript(scriptText);
        task.setResultVariable(resultVariable);
        task.setAutoStoreVariables(StringUtils.isEmpty(autoStoreVariables)?false:Boolean.parseBoolean(autoStoreVariables));
        return task;
    }
}
